<?php

use App\Services\UserService;
use App\Controller\IndexController;

const ENV = 1;
ini_set('date.timezone', 'Asia/Shanghai');
require "./public/payList.html";
require "./public/autoload.php";

if(isset($_REQUEST['type'])){
    $type = $_REQUEST['type'];
    switch($type){
        case 1:
            gzhPay($type, ENV);
            break;
        case 2:
            noRealPay($type, ENV);
            break;
    }
}
function gzhPay($type, $env){
    $config = UserService::getConfig();
	if($env){
        $config = $config['real'];
        $domain = "https://open.wecard.qq.com";
    }else{
        $config = $config['noReal'];
        $domain = "https://tygate.weixiao.qq.com";
    }
    $redirectUri = "https://www.lican.xyz:80/weixiao/index.php?type=$type";
    $encodeUri = urlencode($redirectUri);
    $oauthUrl = "{$domain}/connect/oauth/authorize?app_key={$config['app_key']}&response_type=code&scope=snsapi_userinfo&school_code={$config['school_code']}&redirect_uri={$encodeUri}&state=STATE";
    if(isset($_REQUEST['wxcode'])){ //授权后
        $wxcode = $_REQUEST['wxcode'];
        $accessToken = UserService::getAccessToken($wxcode, $redirectUri, $env);
        $userInfo = UserService::getUserInfo($accessToken, $env);
        $cardNumber = $userInfo['card_number'];//得到进入应用的用户卡号
//        $cardNumber = "68686868";//得到进入应用的用户卡号
        header("location:https://www.lican.xyz:80/weixiao/pay.php?card_number=$cardNumber&env=$env");
    }else{ //授权前
        header("location:{$oauthUrl}");
    }
}

function noRealPay($type, $env){
    //获取用户的openid
    $config = UserService::getConfig();
    if($env){
        $config = $config['real'];
        $domain = "https://payapi.weixiao.qq.com/midas/app";
    }else{
        $config = $config['noReal'];
        $domain = "https://payapidev.weixiao.qq.com/midas/app";
    }
    $redirectUri = "https://www.lican.xyz:80/weixiao/index.php?type=$type";
    $encodeUri = urlencode($redirectUri);
    $oauthUrl = "{$domain}/oauth-openid?sub_appid={$config['sub_appid']}&school_code={$config['school_code']}&app_key={$config['app_key']}&redirect_uri={$encodeUri}";

    if(isset($_REQUEST['openid'])){ //授权后
        $openid = $_REQUEST['openid']; //得到进入应用的用户openid
        header("location:https://www.lican.xyz:80/weixiao/pay.php?openid={$openid}&env=$env");
    }else{ //授权前
        header("location:{$oauthUrl}");
    }
}



